require.config({
    paths: {
        'columntoggle': '../addons/facrm/js/columntoggle',
    }
});
var index = 1;
define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'columntoggle'], function ($, undefined, Backend, Table, Form, Columntoggle) {

    var Controller = {
        index: function (params) {
            var select = Backend.api.query('select');
            select = select == '1' ? true : false;
            var toggle_show_key="searchcontract";
            var toggle_show=localStorage.getItem(toggle_show_key)==0?false:true;
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: (params ? params.index_url : 'facrm/contract/index/index') + (customer_id ? '/customer_id/' + customer_id : ''),
                    add_url: 'facrm/contract/index/add',
                    edit_url: 'facrm/contract/index/edit',
                    del_url: 'facrm/contract/index/del',
                    multi_url: '',
                    table: '',
                }
            });
            var check_status={0: __('待审核'), 1: __('审核中'), 2: __('审核通过'), 3: __('审核未通过')};

            var table = $("#contract");
            //在普通搜索渲染后
            table.on('post-common-search.bs.table', function (event, table) {
                var form = $("form", table.$commonsearch);
                $(".commonsearch-table select[name=scene_id]").val(params ? params.scene_id : 'all');
                if (from_type == "expire") {
                    //快过期合同
                    $(".commonsearch-table").removeClass("hidden");
                    $("input[name='end_time']").val(Moment().year(Moment().year() - 1).startOf('year').format('YYYY-MM-DD H:mm:ss') + ' - ' + Moment().day(Moment().day() + 30).endOf('day').format('YYYY-MM-DD H:mm:ss'));
                    $(".commonsearch-table select[name=check_status]").val(2);
                    $(".commonsearch-table select[name=expire_handle]").val(0);

                } else if (from_type == "return") {
                    //待回款的合同
                    $(".commonsearch-table").removeClass("hidden");
                    $(".commonsearch-table select[name=check_status]").val(2);
                    $(".commonsearch-table select[name=expire_handle]").val(100);
                }
            });
            var columnss = [
                {checkbox: true},

                {
                    field: 'scene_id',
                    title: __('场景'),
                    visible: false,
                    formatter: function (v, r) {
                        return scene_list[v];
                    }, searchList: scene_list
                },

                {
                    field: 'expire_handle',
                    title: __('处理状态'),
                    visible: false,
                    searchList: {0: __('未处理'), 1: __('已续签'), 2: __('不再合作'), 100: __("待回款")}
                },

            ];


            if (Config.fields && Object.keys(Config.fields).length > 0) {
                var fields = JSON.parse(Config.fields);
                for (var i = 0; i < fields.length; i++) {
                    if (fields[i].hasOwnProperty('formatter'))
                        fields[i].formatter = eval(fields[i].formatter);
                    if (fields[i].hasOwnProperty('events'))
                        fields[i].events = eval(fields[i].events);
                    if (fields[i].hasOwnProperty('searchList'))
                        fields[i].searchList = eval(fields[i].searchList);
                    if (fields[i].hasOwnProperty('cellStyle'))
                        fields[i].cellStyle = eval(fields[i].cellStyle);

                    columnss.push(fields[i]);
                }
            }


            //追加操作字段
            if (select) {
                //如果是选择
                columnss.push({
                    field: 'operate', title: __('Operate'), events: {
                        'click .btn-chooseone': function (e, value, row, index) {
                            Fast.api.close(row);
                        },
                    },
                    formatter: function () {
                        return '<a href="javascript:;" class="btn btn-danger btn-chooseone btn-xs"><i class="fa fa-check"></i> ' + __('Choose') + '</a>';
                    }
                });
            } else {
                columnss.push({
                    field: 'operate',
                    title: __('Operate'),
                    table: table,
                    buttons: [
                        {
                            name: 'raddurl',
                            text: __('收款'),
                            title: __('收款'),
                            classname: 'btn btn-xs btn-info  btn-dialog',
                            url: raddurl

                        },
                        {
                            name: 'payurl',
                            text: '',
                            title: __('线上续费收款码'),
                            icon: 'fa fa-qrcode',
                            classname: 'btn btn-xs btn-danger  btn-dialog',
                            url: 'facrm/contract/index/payurl',
                            hidden: function (row) {
                                if (row.check_status == undefined || row.check_status != 2) {
                                    return true;
                                }
                                if (!Config.payConfig || Config.payConfig.online_pay != '1') {
                                    return true;
                                }
                                //判断是否逾期
                                var newtime = Math.round(new Date().getTime() / 1000).toString();
                                if (newtime < (row.end_time - (Config.payConfig.renew_day * 86400))) {
                                    return true;
                                }
                            },
                            success: function () {
                                $(".btn-refresh").trigger('click');
                            }
                        },

                        {
                            name: 'log',
                            text: __('日志'),
                            title: __('审核日志'),
                            classname: 'btn btn-xs btn-success  btn-dialog',
                            url: function (row) {
                                return 'facrm/flow/log/index/flow_id/' + row.flow_id + "/types_id/" + row.id;
                            }

                        },
                        {
                            name: 'verify',
                            text: '审核',
                            title: '去审核',
                            classname: 'btn btn-xs btn-primary  btn-dialog',
                            url: "facrm/backlog/verify/types/contract",
                            hidden: function (row) {

                                if (row.flow_admin_id == "") return true;
                                if ($.inArray(row.check_status, [2, 3]) == 1) return true;
                                var admin_id_arr = row.flow_admin_id.split(',');
                                if ($.inArray(Config.admin_id + "", admin_id_arr) == -1) return true;

                                return false
                            }

                        },

                    ],
                    events: Table.api.events.operate,
                    formatter: Table.api.formatter.operate,
                });
            }

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    columnss
                ],
                onLoadSuccess: function () {
                    // 载入成功时执行
                    loadSuccess("contract")
                },
                onColumnSwitch: function () {
                    // 切换列时执行columnSwitch方法
                    columnSwitch("contract", "contract_table")
                },
                //启用固定列
                fixedColumns: true,
                //固定右侧列数
                fixedRightNumber: 1,
                searchFormVisible: select ? false : toggle_show, //打开搜索
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            $(".btn-print").on("click", function () {
                var ids = Table.api.selectedids(table);

                if (Config.hiprint) {
                    Backend.api.addtabs("hiprint/index/print/ids/" + ids + "?source=" + encodeURIComponent('\\app\\admin\\model\\facrm\\Contract'), "打印");
                } else {
                    Fast.api.open("facrm/contract/index/print/ids/" + ids);
                }
            });

            $("button[name='commonSearch']").bind("click",function(){
                localStorage.setItem(toggle_show_key,(toggle_show?0:1));
            });

        },
        lists: function () {

            Controller.index({
                index_url: 'facrm/contract/index/lists', 'scene_id': 'owner'
            });
        },
        add: function () {
            Controller.api.bindevent();
            Controller.api.businessselect();


            $(function () {
                $("#number-create").on("click", function () {
                    //{:Y}{:m}{:d}{:h}{:i}{:s}{:rand}
                    var vNow = new Date(), sNow = '';
                    sNow = Config.cprefix.replace('{:Y}', vNow.getFullYear());
                    sNow = sNow.replace('{:m}', PrefixZero(vNow.getMonth() + 1, 2));
                    sNow = sNow.replace('{:d}', PrefixZero(vNow.getDate(), 2));
                    sNow = sNow.replace('{:h}', PrefixZero(vNow.getHours(), 2));
                    sNow = sNow.replace('{:i}', vNow.getMinutes());
                    sNow = sNow.replace('{:s}', vNow.getSeconds());
                    sNow = sNow.replace('{:rand}', PrefixZero(vNow.getMilliseconds(), 6));
                    $("input[name^='row[number]']").val(sNow);
                });

                setnums();
                $('#myModal').on('hidden.bs.modal', function () {
                    $('#table1').bootstrapTable('destroy');
                });
                $('#modelProduct').on('show.bs.modal', function (e) {
                    // console.log(btn)
                    var btn = $(e.relatedTarget)
                    // console.log(e)
                    Controller.api.getProduct(btn);
                });
                $('#modelProduct').on('hidden.bs.modal', function () {
                    $('#table2').bootstrapTable('destroy');
                });
                //计算费率
                $('#totalMoneys').on('blur', function () {
                    var len = $('#table tr').length;
                    var total = 0;
                    for (var b = 1; b < len - 1; b++) {
                        var str = '#table tr:eq(' + b + ') .subtotal';
                        var a = $(str).text();
                        if (a == "") {
                            a = 0;
                        }
                        a = parseFloat(a);
                        if (a == "NaN" || a == "" || a == undefined) {
                            a = 0;
                        }
                        total += a;
                    }
                    $("#table #allMoney").text(total);
                    var totalMoney = parseFloat($("#totalMoneys").val());
                    totalMoney = totalMoney.toFixed(2);
                    var rate = parseFloat((total - totalMoney) / total * 100);
                    if (rate < 0) {
                        rate = 0;
                    }
                    $("#c-rate").val(rate.toFixed(2));
                    $("#money").val(total);
                    $("#totalMoneys").val(totalMoney);
                });


            });

            function PrefixZero(num, n) {
                return (Array(n).join(0) + num).slice(-n);
            }
        },
        contractadd: function () {
            Controller.add();
        },
        edit: function () {
            Controller.api.bindevent();
            index = $('#table tr').length - 1;
            $(function () {
                setnums();
                $('#myModal').on('hidden.bs.modal', function () {
                    $('#table1').bootstrapTable('destroy');
                });
                $('#modelProduct').on('show.bs.modal', function (e) {
                    // console.log(btn)
                    var btn = $(e.relatedTarget)
                    // console.log(e)
                    Controller.api.getProduct(btn);
                });
                $('#modelProduct').on('hidden.bs.modal', function () {
                    $('#table2').bootstrapTable('destroy');
                });
                //计算费率
                $('#totalMoneys').on('blur', function () {
                    var len = $('#table tr').length;
                    var total = 0;
                    for (var b = 1; b < len - 1; b++) {
                        var str = '#table tr:eq(' + b + ') .subtotal';
                        var a = $(str).text();
                        if (a == "") {
                            a = 0;
                        }
                        a = parseFloat(a);
                        if (a == "NaN" || a == "" || a == undefined) {
                            a = 0;
                        }
                        total += a;
                    }
                    $("#table #allMoney").text(total);
                    var totalMoney = parseFloat($("#totalMoneys").val());
                    totalMoney = totalMoney.toFixed(2);
                    var rate = parseFloat((total - totalMoney) / total * 100);
                    if (rate < 0) {
                        rate = 0;
                    }
                    $("#c-rate").val(rate.toFixed(2));
                    $("#money").val(total);
                    $("#totalMoneys").val(totalMoney);
                });


            });
            $("#c-contacts_id").data("params", function () {
                const customer_id = $("#c-customer_id").val();
                return {custom: {customer_id: customer_id}};
            });

        },
        change: function () {
            Controller.edit();
        },
        print: function () {
            window.print();
            parent.layer.closeAll();

        },
        detail: function () {
            Controller.edit();
            Table.api.init({
                extend: {
                    index_url: 'facrm/operatelog/index/contract_id/' + contract_id,
                    del_url: 'facrm/operatelog/del',
					plan: 'facrm/contract/index/plan/ids/' + contract_id,
                }
            });
            var operatelog = $("#operatelog");
            operatelog.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                toolbar: '#toolbar-files',
                //禁用默认搜索
                search: false,
                //启用普通表单搜索
                commonSearch: false,
                //可以控制是否默认显示搜索单表,false则隐藏,默认为false
                searchFormVisible: false,
                //分页大小
                pageSize: 10,
                showColumns: false,
                showToggle: false,
                showExport: false,
                showSearch: false,
                columns: [
                    [
                        {field: 'title', title: __('说明'), operate: false},
                        {
                            field: 'nickname', title: __('员工'), formatter: function (value, row) {
                                return value + "(" + row.admin_id + ")";
                            }
                        },
                        {
                            field: 'create_time',
                            title: __('创建时间'),
                            formatter: Table.api.formatter.datetime,
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            sortable: true
                        },
                        {
                            field: 'operate', title: __('Operate'), table: operatelog,
                            events: Table.api.events.operate,
                            buttons: [{
                                name: 'detail',
                                text: __('Detail'),
                                icon: 'fa fa-list',
                                classname: 'btn btn-info btn-xs btn-detail btn-dialog',
                                url: 'facrm/operatelog/detail'
                            }],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ],
            });
			    //回款计划
            var tableplan  = $("#plantable");
            tableplan.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.plan,
                pk: 'id',
                sortName: 'id',
                toolbar: '#toolbar-plan',
                //禁用默认搜索
                search: false,
                //启用普通表单搜索
                commonSearch: false,
                //可以控制是否默认显示搜索单表,false则隐藏,默认为false
                searchFormVisible: false,
                //分页大小
                pageSize: 10,
                showColumns: false,
                showToggle: false,
                showExport: false,
                showSearch: false,
                columns: [
                    [

                        {field: 'id', title: __('Id')},
                        {
                            field: 'name',
                            title: __('计划名称'),
                            operate: 'LIKE',
                            table: table,
                            class: 'autocontent',
                            formatter: Table.api.formatter.content
                        },
                        {field: 'money', title: __('金额'), operate: 'BETWEEN'},
                        {field: 'status', title: __('状态'), formatter: Table.api.formatter.status, searchList: {'-1':'到期未回款',0:'进行中',2:'已回款'}},

                        {
                            field: 'remarks',
                            title: __('备注'),
                            operate: 'LIKE',
                            table: table,
                            class: 'autocontent',
                            formatter: Table.api.formatter.content
                        },
                        {
                            field: 'plan_time',
                            title: __('计划时间'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            datetimeFormat:"YYYY-MM-DD",
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'create_time',
                            title: __('创建时间'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },

                    ]
                ]
            });

			
        },
        selectbusiness: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'facrm/contract/index/selectbusiness',
                    add_url: '',
                    edit_url: '',
                    del_url: '',
                    multi_url: '',
                    table: '',
                }
            });

            var table = $("#table");
            //在普通搜索渲染后
            table.on('post-common-search.bs.table', function (event, table) {
            });
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {field: 'id', title: 'ID'},
                        {field: 'name', title: __('商机名称'), operate: "LIKE"},

                        {
                            field: 'customer',
                            title: __('客户名称'),
                            operate: false,
                            search: false,
                            formatter: function (value, row, index) {
                                if (!row.customer) return '-';
                                value = '<a href="javascript:void(0);" data-url="facrm/customer/index/detail/ids/' + row.customer_id
                                    + '" data-area="[&quot;98%&quot;,&quot;98%&quot;]" class="btn-dialog" data-title="' + row.customer.name + '">' + row.customer.name + '(' + row.customer_id + ')' + '</a>';
                                return value;
                            }
                        },
                        {
                            field: 'customer_id', title: __('客户'), visible: false,
                            addclass: 'selectpage',
                            extend: 'data-source="facrm/customer/index?filter=%7B\"scene_id\"%3A\"7\"%7D" data-field="name" data-orderBy="id desc"'
                        },
                        {field: 'money', title: __('客户预算'), operate: 'BETWEEN', sortable: true},
                        {field: 'remark', title: __('备注'), operate: 'LIKE'},
                        {
                            field: 'deal_time',
                            title: __('预计成交'),
                            formatter: Table.api.formatter.datetime,
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            sortable: true,
                            extend: 'autocomplete="off"'
                        },
                        {field: 'owner_user.nickname', title: __('负责人'), operate: false, search: false},
                        {
                            field: 'owner_user_id', title: __('负责人'), visible: false,
                            addclass: 'selectpage',
                            extend: 'data-source="facrm/common/selectpage/model/admin?type=all" data-field="nickname" data-orderBy="id desc"'
                        },
                        {
                            field: 'update_time',
                            title: __('更新时间'),
                            formatter: Table.api.formatter.datetime,
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            sortable: true,
                            extend: 'autocomplete="off"'
                        },
                        {
                            field: 'is_end',
                            title: __('Status'),
                            formatter: Table.api.formatter.status,
                            searchList: {1: __('已成交'), 0: __('未成交'), 2: __('失败'), 3: __('无效')}
                        },
                        {
                            field: 'operate', title: __('Operate'), events: {
                                'click .btn-chooseone': function (e, value, row, index) {
                                    Fast.api.close(row);
                                },
                            },

                            formatter: function () {
                                return '<a href="javascript:;" class="btn btn-danger btn-chooseone btn-xs"><i class="fa fa-check"></i> ' + __('Choose') + '</a>';
                            }
                        }

                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'facrm/contract/index/recyclebin',
                }
            });


            var table = $("#table");
            //在普通搜索渲染后
            table.on('post-common-search.bs.table', function (event, table) {
                var form = $("form", table.$commonsearch);
                $(".commonsearch-table select[name=scene_id]").val(1);
            });
            var columnss = [
                {checkbox: true},
                {field: 'id', title: 'ID'},
                {field: 'number', title: __('合同编号'), operate: "LIKE"},
                {field: 'name', title: __('合同名称'), operate: "LIKE"},
                {field: 'customer.name', title: __('客户名称'), operate: false, search: false},
                {
                    field: 'customer_id', title: __('客户'), visible: false,
                    addclass: 'selectpage',
                    extend: 'data-source="facrm/customer/index?filter=%7B\"scene_id\"%3A\"7\"%7D" data-field="name" data-orderBy="id desc"'
                },
                {field: 'money', title: __('合同金额'), operate: 'BETWEEN', sortable: true},
                {field: 'return_money', title: __('回款金额'), operate: 'BETWEEN', sortable: true},
                {field: 'create_user.nickname', title: __('创建人'), operate: false, search: false},
                {
                    field: 'create_user_id', title: __('创建人'), visible: false,
                    addclass: 'selectpage',
                    extend: 'data-source="facrm/common/selectpage/model/admin?type=all" data-field="nickname" data-orderBy="id desc"'
                },
                {field: 'order_admin.nickname', title: __('签约人'), operate: false, search: false},
                {
                    field: 'order_admin_id', title: __('签约人'), visible: false,
                    addclass: 'selectpage',
                    extend: 'data-source="facrm/common/selectpage/model/admin?type=all" data-field="nickname" data-orderBy="id desc"'
                },

                {
                    field: 'check_status',
                    title: __('Status'),
                    formatter: Table.api.formatter.status,
                    searchList: {0: __('待审核'), 1: __('审核中'), 2: __('审核通过'), 3: __('审核未通过')}
                },
                {
                    field: 'expire_handle',
                    title: __('处理状态'),
                    visible: false,
                    searchList: {0: __('未处理'), 1: __('已续签'), 2: __('不再合作'), 100: __("待回款")}
                },
                {
                    field: 'operate',
                    width: '130px',
                    title: __('Operate'),
                    table: table,
                    events: Table.api.events.operate,
                    buttons: [
                        {
                            name: 'Restore',
                            text: __('Restore'),
                            classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                            icon: 'fa fa-rotate-left',
                            url: 'facrm/contract/index/restore',
                            refresh: true
                        },
                        {
                            name: 'Destroy',
                            text: __('Destroy'),
                            classname: 'btn btn-xs btn-danger btn-ajax  btn-destroyit',
                            icon: 'fa fa-times',
                            url: 'facrm/contract/index/destroy',
                            refresh: true
                        }
                    ],
                    formatter: Table.api.formatter.operate
                }
            ];

            if (Config.fields && Object.keys(Config.fields).length > 0) {
                var fields = JSON.parse(Config.fields);
                var start = 20;
                for (var i = 0; i < fields.length; i++) {
                    columnss.splice(start + i, 0, fields[i]);
                }
            }

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    columnss
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            // 绑定TAB事件
            $('.panel-heading ul[data-field] li a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                var field = $(this).closest("ul").data("field");
                var value = $(this).data("value");
                $(".commonsearch-table input[name=" + field + "]").val(value);
                return false;
            });
        },
        diyorder:function(){
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
                if ("undefined" == typeof contract_id) {
                    contract_id = 0;
                }
                Fast.api.ajax({
                    type: 'GET',
                    url: 'facrm/fields/get_fields_html',
                    data: {source: 'contract', 'id': contract_id}
                }, function (data) {
                    $("#extend").html(data.html);
                    Form.api.bindevent($("#extend"));
                    return false;
                }, function () {
                    return false;
                });
            },
            getProduct: function (btn) {
                Table.api.init({
                    extend: {
                        index_url: 'facrm/product/product/index'
                    }
                });
                var table = $("#table2");

                // 初始化表格
                table.bootstrapTable({
                    url: $.fn.bootstrapTable.defaults.extend.index_url,
                    pk: 'id',
                    sortName: 'id',
                    commonSearch: false,
                    escape: false,
                    columns: [
                        [{
                            field: 'operate', title: __('Operate'), events: {
                                'click .btn-chooseone': function (e, value, row, index) {
                                    var _this = btn.parent().parent();
                                    var temp_index = _this.find(".find").data("index");
                                    _this.find(".find").val(row.name);
                                    _this.find("input[name='product[" + temp_index + "][product_id]']").val(row.id);
                                    _this.find(".unit").text(row.unit);
                                    _this.find("td:eq(2)").text(row.sku);
                                    _this.find("td:eq(7)").text(row.specification);

                                    _this.find(".unit-price").val(row.price);

                                    _this.find("input[name='product[" + temp_index + "][sku]']").val(row.sku);
                                    _this.find("input[name='product[" + temp_index + "][specification]']").val(row.specification);
                                    _this.find("input[name='product[" + temp_index + "][unit]']").val(row.unit);
                                    _this.find("input[name='product[" + temp_index + "][nums]']").val(1);
                                    if (row.prop != "" && row.prop != null) {
                                        var arr = JSON.parse(row.prop);
                                        var str = "";
                                        var temp_str = "";
                                        for (var i = 0; i < arr.length; i++) {
                                            if (typeof (arr[i]['value']) != "undefined" && arr[i]['value'] !== null) {
                                                str += arr[i]['title'] + ":" + arr[i]['value'] + "; <br>";
                                                temp_str += arr[i]['title'] + ":" + arr[i]['value'] + "; |";
                                            }
                                        }
                                        _this.find("td:eq(8)").html(str);
                                        _this.find("input[name='product[" + temp_index + "][prop]']").val(temp_str);
                                    }
                                    totalNums(_this.find("input[name='product[" + temp_index + "][nums]']"));
                                    $('#modelProduct').modal('hide');
                                },
                            }, formatter: function (val, row) {
                                if (row.inventory <= 0) return '无库存';
                                return '<a href="javascript:;" class="btn btn-danger btn-chooseone btn-xs"><i class="fa fa-check"></i> ' + __('Choose') + '</a>';
                            }
                        },
                            {
                                field: 'sku',
                                title: __('编码')
                            },
                            {
                                field: 'name',
                                title: __('Name')
                            },
                            {
                                field: 'price',
                                title: __('价格')
                            },
                            {
                                field: 'inventory',
                                title: __('库存')
                            },
                            {
                                field: 'specification',
                                title: __('规格')
                            },

                            {
                                field: 'prop',
                                title: __('属性'),
                                formatter: function (value, row, index) {
                                    var str = "";
                                    if (row.prop != "" && row.prop != null) {
                                        var arr = JSON.parse(row.prop);
                                        for (var i = 0; i < arr.length; i++) {
                                            if (typeof (arr[i]['value']) != "undefined" && arr[i]['value'] !== null) {
                                                str += arr[i]['title'] + ":" + arr[i]['value'] + ";<br>";
                                            }
                                        }
                                    }
                                    return str;
                                }
                            },


                        ]
                    ]
                });
                Table.api.bindevent(table);

            },
            businessselect: function () {
                $("#c-customer_id").bind("change", function () {
                    var customer_id = $("#c-customer_id").val();
                    $('.business_id_div').show();
                    $("#select-resources").html("点击请选择");
                    $("input[name='row[business_id]']").val(0);
                    if (customer_id) {
                        $("#c-contacts_id").removeAttr('disabled');
                        $("#c-contacts_id_text").removeAttr('disabled');
                    }


                });
                $("#c-contacts_id").data("params", function () {
                    const customer_id = $("input[name='row[customer_id]']").val();
                    return {custom: {customer_id: customer_id}};
                });
                var refreshkey = function (data) {
                    var business_id = data.id;
                    $("input[name='row[business_id]']").val(data.id).trigger("change");
                    $("#select-resources").html(data.name);
                    $('#c-order_admin_id').val(data.owner_user_id);
                    $('#c-order_admin_id').selectPageRefresh();
                    $('#c-customer_id').val(data.customer_id);
                    $('#c-customer_id').selectPageRefresh();
                    $("#c-contacts_id").removeAttr('disabled');
                    $("#c-contacts_id_text").removeAttr('disabled');

                    //自动加载商机里的产品
                    console.log(data);
                    $.ajax({
                        type: 'POST',
                        url: 'facrm/business/index/product',
                        data: {business_id: business_id},
                        dataType: 'json',
                        success: function (data) {
                            if (data.total > 0) {
                                $.each(data.rows, function (i, j) {
                                    addRow(j);
                                });

                            } else {
                                Toastr.error("商机没有填商品");
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            Toastr.error("请求错误");
                        }
                    });


                };
                $(document).on('click', "#select-resources", function () {
                    var customer_id = $("input[name='row[customer_id]']").val();
                    parent.Backend.api.open($(this).data("url") + "?customer_id=" + customer_id, __('Select'), {callback: refreshkey});
                    return false;
                });
            },
            formatter: {
                thumb: function (value, row, index) {
                    if (!value) return '';
                    value = value === null ? '' : value.toString();
                    var arr = value.split(',');
                    var html = [];
                    $.each(arr, function (i, value) {

                        var reg = /\.(png|jpg|gif|jpeg|webp)$/;
                        if (reg.test(value)) {
                            html.push('<a href="' + Fast.api.cdnurl(value) + '" target="_blank"><img src="' + Fast.api.cdnurl(value) + '" alt="" style="max-height:90px;max-width:120px"></a>');
                        } else {
                            if (row.imagetype == undefined) row.imagetype = /[^\.]+$/.exec(value);
                            html.push('<a href="' + Fast.api.cdnurl(value) + '" target="_blank"><img src="' + Fast.api.fixurl("ajax/icon") + "?suffix=" + row.imagetype + '" alt="" style="max-height:90px;max-width:120px"></a>');
                        }
                    });
                    return html.join(' ');
                },
                url: function (value, row, index) {
                    return '<a href="' + row.fullurl + '" target="_blank" class="label bg-green">' + row.url + '</a>';
                },
                filename: function (value, row, index) {
                    return '<div style="width:180px;margin:0 auto;text-align:center;overflow:hidden;white-space: nowrap;text-overflow: ellipsis;">' + Table.api.formatter.search.call(this, value, row, index) + '</div>';
                },
                datetime: function (value, row, index) {
                    var datetimeFormat = typeof this.datetimeFormat === 'undefined' ? 'YYYY/MM/DD HH:mm' : this.datetimeFormat;
                    if (isNaN(value)) {
                        return value ? Moment(value).format(datetimeFormat) : __('None');
                    } else {
                        return value ? Moment(parseInt(value) * 1000).format(datetimeFormat) : __('None');
                    }
                },
            }
        }
    };
    return Controller;
});

// 添加
function addRow(data) {

    var name = "";
    var product_id = "";
    var sku = "";
    var specification = "";
    var prop = "";
    var unit = "";
    var nums = "";
    var subtotal = "0";
    var remarks = "";
    var price = "";
    if (data && Object.keys(data).length > 0) {
        console.log(data);
        name = data.info.name;
        product_id = data.product_id;
        sku = data.info.sku;
        specification = data.info.specification;
        prop = prop_handle(data.info.prop);
        unit = data.info.unit;
        nums = data.nums;
        subtotal = data.subtotal;
        remarks = data.remarks;
        price = data.price;
    }

    var len = $('#table tr').length - 1;
    var lens = len - 2;
    var tempTr = '<tr>' +
        '<td> <button type="button" class="btn btn-primary" onclick="addRow()">添加</button><button type="button" class="btn btn-default" onclick="delRow(this)" >删除</button> </td>' +
        '<td>' + len + '</td>' +
        '<td>' + sku + '</td>' +
        '<td><input style="width: 100px" value="' + name + '" data-index="' + index + '" type="text" name="product[' + index + '][name]" class="find" data-toggle="modal" data-target="#modelProduct" data-rule="">' +
        '<input   type="hidden" name="product[' + index + '][product_id]" value="' + product_id + '">' +
        '<input   type="hidden" name="product[' + index + '][sku]" value="' + sku + '">' +
        '<input   type="hidden" name="product[' + index + '][specification]" value="' + specification + '">' +
        '<input   type="hidden" name="product[' + index + '][prop]" value="' + prop + '">' +
        '<input   type="hidden" name="product[' + index + '][unit]" value="' + unit + '"></td>' +
        '<td><input style="width: 80px"  type="number" value="' + nums + '" name="product[' + index + '][nums]" data-rule="required;integer;range(0~);" class="nums" onchange="totalNums(this)" onblur="totalNums(this)"></td>' +
        '<td><input style="width: 80px" type="number" value="' + price + '" data-rule="required;range(0~);" name="product[' + index + '][price]" onchange="calMoney(this)" onblur="calMoney(this)"  class="unit-price" >' +
        '<td><textarea rows="1" class="remarks" cols="20" name="product[' + index + '][remarks]">' + remarks + '</textarea></td>' +
        '<td>' + specification + '</td>' +
        '<td>' + prop + '</td>' +
        '<td class="unit">' + unit + '</td>' +
        '<input   type="hidden" name="product[' + index + '][subtotal]" value="' + subtotal + '"   ></td>' +
        '<td class="subtotal">' + subtotal + '</td>' +
        '</tr>';
    $('#table tbody tr:eq(' + lens + ')').after(tempTr);
    $(document).ready(function () {
        $("input[name='product[" + index + "][name]']").trigger("click");
    })
    index++;

}

// 删除
function delRow(obj) {

    if ($('#table tbody tr').length == 2) {
        alert(__("Can't delete"));
        return false;
    }
    $(obj).parent().parent().remove();
    totalNums(null);
    calTotalMoneys()
    setnums();
}

//设置序号
function setnums() {
    var len = $('#table tr').length;
    for (var i = 1; i < len - 1; i++) {
        $('#table tr:eq(' + i + ') td:nth-child(2)').text(i);
    }
}

//计算总数量
function totalNums(obj) {
    var len = $('#table tr').length;
    var total = 0;
    if (obj != null) {
        calMoney(obj);
    }
    for (var i = 1; i < len - 1; i++) {
        var nums = $('#table tr:eq(' + i + ') .nums').val();
        if (nums == "") {
            nums = 0;
        } else {
            nums = getNumValue(nums);
            if (nums == false || nums < 0) {
                total = false;
                return false;
            }
        }

        total += nums;
    }
    if (total != false) {
        $(".totalnums").text(total);

        $("#allNums").val(total);
    }
}

function getNumValue(num) {
    if (!isNaN(num) && num != "") {
        num = parseFloat(num);
        var a = isPositiveInteger(num)
        if (a == false) {
            num = false;
        }
    } else {
        num = false;
    }
    return num;
}

function isInteger(obj) {
    return obj % 1 === 0
}

function isPositiveInteger(s) { //是否为正整数
    var re = /^[0-9]+$/;
    return re.test(s)
}

// 小计
function calMoney(obj) {
    var total = 0;
    var nums = $(obj).parent().parent().find(".nums").val();
    var nuitprice = $(obj).parent().parent().find(".unit-price").val();
    if (nuitprice == "") {
        return false;
    }
    nuitprice = parseFloat(nuitprice);
    nums = getNumValue(nums);
    if (nums == false) {
        return false;
    }
    total = nuitprice * nums;
    total = total.toFixed(2);
    $(obj).parent().parent().find(".subtotal").text(total);
    var temp_index = $(obj).parent().parent().find(".find").data("index");
    $(obj).parent().parent().find("input[name='product[" + temp_index + "][subtotal]']").val(total);
    calTotalMoneys();
}

// 计算总金额
function calTotalMoneys() {
    var len = $('#table tr').length;
    var total = 0;
    for (var b = 1; b < len - 1; b++) {
        var str = '#table tr:eq(' + b + ') .subtotal';
        var a = $(str).text();
        if (a == "") {
            a = 0;
        }
        a = parseFloat(a);
        if (a == "NaN" || a == "" || a == undefined) {
            a = 0;
        }
        total += a;
    }
    $("#table #allMoney").text(total);
    var rate = $("#c-rate").val();
    rate = parseFloat(rate);
    var totalMoney = total * (1 - rate / 100);
    // var totalMoney = total;
    $("#money").val(total);
    totalMoney = totalMoney.toFixed(2);
    $("#totalMoneys").val(totalMoney);

}

/**
 * 处理属性
 * @param prop
 */
function prop_handle(prop) {
    var arr = [];
    var str = "";
    if (!typeof obj == 'object' && !obj.constructor == Array) {
        if (prop != "") {
            var arr = JSON.parse(row.prop);
        }
    }
    if (arr.length > 0) {
        for (var i = 0; i < arr.length; i++) {
            if (typeof (arr[i]['value']) != "undefined" && arr[i]['value'] !== null) {
                str += arr[i]['title'] + ":" + arr[i]['value'] + ";<br>";
            }
        }
    }
    return str;
}

